package flextv.main.command {

import com.adobe.cairngorm.commands.ICommand;
import com.adobe.cairngorm.control.CairngormEvent;

import flash.filesystem.File;

import flextv.core.logic.CoreModel;
import flextv.core.logic.Logger;
import flextv.core.logic.Util;
import flextv.core.vo.Playlist;
import flextv.core.vo.StoredItem;
import flextv.main.event.DeleteStoredItemEvent;
import flextv.main.logic.MainServices;

import mx.logging.ILogger;

public class DeleteStoredItemCommand implements ICommand {
	
	private static const LOG: ILogger = Logger.getLog(DeleteStoredItemCommand);
	
	public function DeleteStoredItemCommand() {
	}

	public function execute(_event: CairngormEvent): void {
		const event: DeleteStoredItemEvent = _event as DeleteStoredItemEvent;
		LOG.info("Executing [event=" + event + "].");
		
		const item: StoredItem = event.storedItem;
		
		
		if(CoreModel.instance.currentStoredItem == item) {
			LOG.debug("CoreModel.instance.currentStoredItem = null");
			CoreModel.instance.currentStoredItem = null;
		}
		
		var parentPlaylist: Playlist = null;
		for each(var p: Playlist in CoreModel.instance.playlists) {
			if(p.id == item.playlistId) {
				parentPlaylist = p;
				break;
			}
		}
		const playlistItemIndex: int = parentPlaylist.storedItems.getItemIndex(item);
		parentPlaylist.storedItems.removeItemAt(playlistItemIndex);
		
		MainServices.instance.persistenceService.deleteStoredItem(item);
		
		const flvFile: File = Util.resolveFlvFile(item);
		if(flvFile.exists == true) {
			LOG.debug("Deleting flv file at ["+flvFile.nativePath+"].");
			flvFile.deleteFile();
		}
		
	}
	
}
}